package com.servlet;

import com.model.Purchase;
import com.service.PurchaseService;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
    PurchaseService ps2 = new PurchaseService();
    HttpServletRequest request;
    HttpServletResponse response;

    @SneakyThrows
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.request = request;
        this.response = response;
        String me = request.getParameter("method");
        if (me.equals("show")) {
            this.show();
        }
        if (me.equals("delete")){
            this.delete();
        }
    }


    private void show() throws ServletException, IOException {
        List<Purchase> purchases = ps2.show();
        System.out.println(purchases.toString());
        request.setAttribute("purchases", purchases);
        request.getRequestDispatcher("purchase/show.jsp").forward(request, response);
    }
    private void delete() throws ServletException, IOException {
        String id = request.getParameter("id");
        ps2.delete(id);
        this.show();
    }
}
